<?php
namespace App\GraphQL\Mutations\Device;

use App\Models\Device;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use Illuminate\Validation\Rule;
use App\Models\DeviceRepairLog;
use App\Models\DeviceLog;

class Repair
{

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        DB::transaction(function () use ($args) {
            $data = $args['input'];
            $id = $args['id'];
            $device = $this->validate($id, $data);
            $log = [
                'user_id' => auth()->user()->id,
                'content' => '维修',
                'level' => 'RED',
                'device_id' => $device->id
            ];
            $repairLog = [
                'user_id' => auth()->user()->id,
                'remark' => $data['remark'],
                'device_id' => $device->id
            ];
            DeviceRepairLog::create($repairLog);
            DeviceLog::create($log);
        });

        return [
            'status' => '200',
            'message' => '维修成功'
        ];
    }

    public function validate($id, $data)
    {
        $rules = [
            'status' => [
                'required',
                Rule::in([
                    'SCRAP',
                    'REPAIR',
                    'FAULT'
                ])
            ],
            'remark' => [
                'required'
            ]
        ];
        $messages = [
            'remark.required' => '维修日志不能为空',
            'status.required' => '状态不能为空',
            'status.in' => '状态超出限制'
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        $old = Device::find($id);
        if (! $old) {
            throw new \Exception('设备不存在!');
        }
        return $old;
    }
}
